package de.slothsoft.wasbinich.android;

import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import de.slothsoft.android.util.WebUtil;
import de.slothsoft.wasbinich.core.ApplicationInfo;
import de.slothsoft.wasbinich.core.WebserviceUrls;
import de.slothsoft.wasbinich.core.database.Database;
import de.slothsoft.wasbinich.core.util.CommonUtil;

public class InfoActivity extends AbstractActivity {

    public static final String WEBSITE = "http://wasbinich-game.de/"; //$NON-NLS-1$

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_info);

	TextView urlTextView = (TextView) findViewById(R.id.info_field_server_url);
	urlTextView.setText(WebserviceUrls.WEBSERVICE_URL);
	updateFieldsFromServerInfo(urlTextView);
	updateFieldsFromClientInfo(urlTextView);
    }

    private void updateFieldsFromServerInfo(final View view) {
	if (WebUtil.isOnline(this)) {
	    new Thread(new Runnable() {
		@Override
		public void run() {
		    try {
			final ApplicationInfo info = Database.getInstance().getApplicationBean().getServerInfo();
			runOnUiThread(new Runnable() {
			    @Override
			    public void run() {
				updateFieldsFromInfo(R.id.info_field_server_version, R.id.info_field_server_pictures,
					R.id.info_field_server_languages, info);
			    }
			});
		    } catch (Exception exception) {
			handleException(exception);
		    }
		}
	    }).start();
	}
	TextView urlView = (TextView) findViewById(R.id.info_field_server_website);
	urlView.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG);
	urlView.setOnClickListener(new View.OnClickListener() {

	    @Override
	    public void onClick(View v) {
		WebUtil.openUrl(InfoActivity.this, WEBSITE);
	    }
	});
    }

    private void updateFieldsFromClientInfo(final View view) {
	new Thread(new Runnable() {
	    @Override
	    public void run() {
		try {
		    final ApplicationInfo info = Database.getInstance().getApplicationBean().getClientInfo();
		    runOnUiThread(new Runnable() {
			@Override
			public void run() {
			    updateFieldsFromInfo(R.id.info_field_client_version, R.id.info_field_client_pictures,
				    R.id.info_field_client_languages, info);
			}
		    });
		} catch (Exception exception) {
		    handleException(exception);
		}
	    }
	}).start();
    }

    private void updateFieldsFromInfo(int versionField, int pictures, int languages, ApplicationInfo info) {
	((TextView) findViewById(versionField)).setText(info.version);
	((TextView) findViewById(pictures)).setText(info.pictureCount < 0 ? "-" : String.valueOf(info.pictureCount)); //$NON-NLS-1$
	((TextView) findViewById(languages)).setText(CommonUtil.createLanguagesString(info.supportedLanguages));
    }

}
